import os, sys, cv2, traceback
import numpy as np

parent_path = os.path.abspath(os.path.join(__file__, *([".."] * 3)))
sys.path.insert(0, parent_path)

import time, threading, yaml
from flask import Flask, request
from gevent import pywsgi, monkey, pool

from core.task.task_pipeline import TaskPipeline
from core.server import Server
from core.utils.logger import logging

# 打补丁，使得标准库中的阻塞式I/O操作变为非阻塞式
# monkey.patch_all()

app = Flask(__name__)


def format_data(org_json):
    if org_json["mode"] == "b64":
        json_data = {
            "id": org_json["id"],
            "tag": "task",
            "data": {
                "tag": org_json["clas"],
                "data": {"tag": "base64", "data": {"input_data": org_json["image"]}},
            },
        }
    elif org_json["mode"] == "restart":
        json_data = {
            "id": org_json["id"],
            "tag": "option",
            "data": {"tag": "restart", "data": None},
        }
    else:
        raise Exception("wrong mode in request json")
    return json_data


# ------ 系统相关api ------


@app.route("/api/option/restart", methods=["get"])
def handle_restart():
    try:
        server.restart()
        return {"code": 200}
    except Exception as e:
        logging.error(traceback.format_exc())


# ------ 功能api ------


@app.route("/api/V1.0/rooftop", methods=["post"])
def handle_rooftop_old():
    """
    该接口为南网AI平台的专用接口, 该接口早期提交后无法再次修改, 所以单独设立
    data:{
        id: 1
        mode: "base64"
        image: "b64_data..."
        clas: ""
        }
    }
    """
    databox = {}
    try:
        code = 200
        message = ""
        logging.info(f"|/api/V1.0/rooftop|")
        json_data = request.json
        json_data = format_data(json_data)
        databox = server.main_request(json_data)
    except Exception as e:
        code = 500
        message = traceback.format_exc()
        logging.error(message)
    response = {
        "code": code,
        "message": message,
        "data": databox["objects"] if databox.get("objects", False) else [],
    }
    logging.info("task id {} done".format(json_data["id"]))
    return response


if __name__ == "__main__":

    # 日志初始化
    log_path = "core/utils/logger_samples/log_cfg.yaml"
    logging.set_config(log_path)

    # 定义后台服务类
    server_cfg_path = os.path.dirname(__file__) + "/configs/server_cfg.yml"
    server = Server(server_cfg_path)

    WSGI_server = pywsgi.WSGIServer(
        ("0.0.0.0", 12682),
        app,
        # spawn=pool.Pool()
    )
    logging.info("|server start|")
    WSGI_server.serve_forever()
    logging.info("|server stop|")
